package com.fw.application.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.UserController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.vo.FootCityVo;
import com.fw.system.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 证券知识大课堂 前端控制器
 * </p>
 *
 * @author ghb
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/web/bond")
@CrossOrigin
@Api(tags = "炸弹与护盾相关")
public class TbBondController implements UserController {

    @Autowired
    private ITbSysRuleService ruleService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private ITbIntegralLogService logService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbNoticeService noticeService;
    @Autowired
    private ITbWechatFootService wechatFootService;

    @GetMapping("/payBond")
    @ApiOperation("兑换护盾或炸弹数量 pram：shield=护盾, bomb=炸弹 ")
    public Result payBond(@RequestParam(required = false) Integer shield, @RequestParam(required = false) Integer bomb) {

        TbSysRule sysRule;
        TbUser user = this.getUser();
        String logName = "兑换护盾";
        int i = 0;
        if (shield != null && !shield.equals(0)) {
            sysRule = ruleService.getById("3");
            i = Integer.parseInt(sysRule.getRuleValue()) * shield;
            if (user.getIntegral() < i)
                return new Result().fail(500, "积分不足");
            user.setIntegral(user.getIntegral() - i);
            user.setShield(user.getShield() + shield);
            userService.updateById(user);
        }

        if (bomb != null && !bomb.equals(0)) {
            sysRule = ruleService.getById("2");
            i = Integer.parseInt(sysRule.getRuleValue()) * bomb;
            if (user.getIntegral() < i)
                return new Result().fail(500, "积分不足");
            user.setIntegral(user.getIntegral() - i);
            user.setBomb(user.getBomb() + bomb);
            userService.updateById(user);
            logName = "兑换炸弹";
        }
        logService.addIntegral(Builder
                .of(TbIntegralLog::new).with(TbIntegralLog::setIntegralName, logName)
                .with(TbIntegralLog::setUserId, user.getId())
                .with(TbIntegralLog::setIntegralNum, i)
                .with(TbIntegralLog::setIsType, 2).build());

        return success();
    }

    @ApiOperation("轰炸功能，回传被轰炸者userId")
    @GetMapping("/userBomb")
    @Transactional(rollbackFor = Exception.class)
    public synchronized Result userBomb(@RequestParam String userId) {

        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0)
            return new Result<FootCityVo>().fail(500, "活动已结束");
        TbUser user = this.getUser();
        if (user.getId().equals(userId))
            return new Result().fail(500, "不可以对自己使用道具哦！");
        TbUser firUser = userService.getById(userId);
        Assert.isTrue(firUser.getWechatFool() > 0, "您不可以对今日步数为0的伙伴下手喔");
        if (user.getBomb() <= 0)
            return new Result().fail(500, "骗桔数量不足");
        if (LocalTime.now().compareTo(LocalTime.parse("20:00:00")) >= 0 && LocalTime.now().compareTo(LocalTime.parse("23:59:59")) <= 0)
            return new Result().fail(500, "轰炸时间未开启");
        Integer dayBomb = Integer.valueOf(ruleService.getById("5").getRuleValue());
        Integer frrDayBomb = Integer.valueOf(ruleService.getById("18").getRuleValue());
        int count = noticeService.count(Wrappers.<TbNotice>lambdaQuery()
                .eq(TbNotice::getUserId, user.getId())
                .eq(TbNotice::getNoticeType, 1)
                .last("and to_days(create_time) = to_days(now())"));
        int firCount = noticeService.count(Wrappers.<TbNotice>lambdaQuery()
                .eq(TbNotice::getGamePlayerUserId, firUser.getId())
                .eq(TbNotice::getNoticeType, 1)
                .last("and to_days(create_time) = to_days(now())"));
        if (count >= dayBomb)
            return new Result().fail(500, "轰炸已达上限");
        if (firCount >= frrDayBomb)
            return new Result().fail(500, "Ta已经达到被轰炸上限，请让Ta休息会吧");
        if (firUser.getShield() > 0) {
            firUser.setShield(firUser.getShield() - 1).updateById();
            user.setBomb(user.getBomb() - 1).updateById();
            //添加护盾记录log
            noticeService.addNoticeLog(
                    Builder.of(TbNotice::new).with(TbNotice::setUserId, firUser.getId())
                            .with(TbNotice::setGamePlayerUserId, user.getId())
                            .with(TbNotice::setNoticeType, 2)
                            .with(TbNotice::setNoticeTitle, user.getNickName() + "炸向了" + firUser.getNickName() +
                                    ",没想到他机智地打开了神秘护盾，化险为夷！").build()
            );
            //添加轰炸记录log
            noticeService.addNoticeLog(
                    Builder.of(TbNotice::new).with(TbNotice::setUserId, user.getId())
                            .with(TbNotice::setGamePlayerUserId, firUser.getId())
                            .with(TbNotice::setIsState, 1)
                            .with(TbNotice::setNoticeType, 1)
                            .with(TbNotice::setNoticeTitle, user.getNickName() + "一声惊雷，炸向了" + firUser.getNickName()).build()
            );
        } else {
            //减少步数，当前有效步数为0减少历史步数
            Integer bombFool = Integer.valueOf(ruleService.getById(12).getRuleValue());
            TbWechatFoot one = wechatFootService.getOne(Wrappers.<TbWechatFoot>lambdaQuery().eq(TbWechatFoot::getUserId, firUser.getId()).
                    last("and to_days(create_time) = to_days(now())"));
            if (firUser.getWechatFool() < bombFool) {
                //将当前步数减少为0
                firUser.setWechatFool(0).updateById();
                one.setWechatFoot(0);
                //减少历史步数
//                if (firUser.getCountFool() < bombFool) {
//                    firUser.setCountFool(0).updateById();
//                } else {
//                    firUser.setCountFool(user.getCountFool() - bombFool).updateById();
//                }
            } else {
                firUser.setWechatFool(firUser.getWechatFool() - bombFool);
                one.setWechatFoot(one.getWechatFoot() - bombFool);
            }
            wechatFootService.updateById(one);
            //介绍用户表累计步数统计字段
            if (firUser.getCountFool() < bombFool) {
                firUser.setCountFool(0).updateById();
            } else {
                firUser.setCountFool(firUser.getCountFool() - bombFool).updateById();
            }
            user.setBomb(user.getBomb() - 1).updateById();

            //添加轰炸记录log
            noticeService.addNoticeLog(
                    Builder.of(TbNotice::new).with(TbNotice::setUserId, user.getId())
                            .with(TbNotice::setGamePlayerUserId, firUser.getId())
                            .with(TbNotice::setNoticeType, 1)
                            .with(TbNotice::setNoticeTitle, user.getNickName() + "一声惊雷，炸向了" + firUser.getNickName()).build());
        }


        return success();
    }

}

